package com.luomo.wenyuan.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * @author LiuMei
 * @date 2020-10-21.
 */
public class FileUtils {

    public static String saveFile(MultipartFile file, String path) {
        File targetFile = new File(path, file.getOriginalFilename());
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return targetFile.getAbsolutePath();
    }

    public static ResponseEntity getFile(String path) {
        if (StrUtil.isNotBlank(path)) {

            File file = new File(path);
            HttpHeaders headers = new HttpHeaders();
            //为了解决中文名称乱码问题
            String fileName = null;
            try {
                fileName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(FileUtil.readBytes(file), headers, HttpStatus.CREATED);
        } else {
            return null;
        }
    }

}
